import React, {useEffect, useState} from "react";
import * as ECharts from 'echarts';

import SystemInfoApi, {MemoryInfo} from "@/api/web/SystemInfoApi.ts";
import useAppState from "@/store/AppState.ts";
import EChartsFC from "@/components/EChartsFC.tsx";
import useThemeStore from "@/store/ThemeStore.ts";
import {IThemeStoreData} from "@/store/LocalStore.ts";
import {Card, Collapse} from "antd";
import {createStyles} from "antd-style";

const doVirtualMemoryGraph = (ins: ECharts.EChartsType, data: MemoryInfo, width: number, theme: IThemeStoreData) => {
    const option: ECharts.EChartsOption =
        {
            backgroundColor: "transparent",
            title: [
                {
                    text: "虚拟内存信息",
                    left: "50%",
                    top: "5%",
                    textAlign: 'center',
                    textStyle: {
                        color: theme.type == 'dark' ? "#ffffff" : "#000000",
                    },
                },
            ],
            series: [
                {
                    name: '虚拟内存',
                    type: 'pie',
                    radius: '50%',
                    top: '5%',
                    data: [
                        {
                            value: data.virtualMemory.virtualInUse,
                            name: '已用',
                            itemStyle: {
                                color: "#" + theme.color,
                            },
                            label: {
                                position: 'inside',
                                color: theme.type == 'dark' ? "#ffffff" : "#000000",
                            },
                        },
                        {
                            value: (data.virtualMemory.virtualMax - data.virtualMemory.virtualInUse),
                            name: '可用',
                            itemStyle: {
                                color: "#" + theme.color + "5f",
                            },
                            label: {
                                position: 'inside',
                                color: theme.type == 'dark' ? "#ffffff" : "#000000",
                            },
                        },
                    ],
                },
            ],
            tooltip: {
                trigger: 'item',
            },
        };
    ins.setOption(option)
}

const doMemoryGraph = (ins: ECharts.EChartsType, data: MemoryInfo, width: number, theme: IThemeStoreData) => {
    const option: ECharts.EChartsOption =
        {
            backgroundColor: "transparent",
            title: [
                {
                    text: "物理内存信息",
                    left: "50%",
                    top: "5%",
                    textAlign: 'center',
                    textStyle: {
                        color: theme.type == 'dark' ? "#ffffff" : "#000000",
                    },
                },
            ],
            series: [
                {
                    name: '物理内存',
                    type: 'pie',
                    radius: '50%',
                    top: '5%',
                    data: [
                        {
                            value: (data.total - data.available),
                            name: '已用',
                            itemStyle: {
                                color: "#" + theme.color,
                            },
                            label: {
                                position: 'inside',
                                color: theme.type == 'dark' ? "#ffffff" : "#000000",
                            },
                        },
                        {
                            value: data.available,
                            name: '可用',
                            itemStyle: {
                                color: "#" + theme.color + "5f",
                            },
                            label: {
                                position: 'inside',
                                color: theme.type == 'dark' ? "#ffffff" : "#000000",
                            },
                        },
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)',
                        },
                    },
                },
            ],
            tooltip: {
                trigger: 'item',
            },
        };
    ins.setOption(option)
}

const useStyles = createStyles(({css, token}) => {
    return {
        container: css`
            display: flex;

            .cardBody {
                background-color: transparent;
                border: none;

                .mCard {
                    p {
                        width: 100%;
                        display: flex;
                        text-align: left;

                        span {
                            margin-left: auto;
                        }
                    }
                }

                .vmCard {
                    li {
                        display: flex;
                        width: 100%;
                        
                        span {
                            margin-left: auto;
                        }
                    }
                }
            }
        `,
    }
})

const MemoryCard: React.FC = () => {
    const width = useAppState(state => state.width)
    const theme = useThemeStore(state => state.theme)
    const [memoryGraphInstance, setMemoryGraphInstance] = useState<ECharts.EChartsType | null>(null)
    const [virtualMemoryGraphInstance, setVirtualMemoryGraphInstance] = useState<ECharts.EChartsType | null>(null)
    const [memoryInfo, setMemoryInfo] = useState<MemoryInfo | null>(null)
    const styles = useStyles().styles;

    const height = 300

    useEffect(() => {
        if (memoryGraphInstance == null) return
        if (virtualMemoryGraphInstance == null) return

        let stopLoop = false
        const loop = async () => {
            if (stopLoop) {
                return
            }
            try {
                const res = await SystemInfoApi.getMemoryInfo();
                setMemoryInfo(res.data)
                if (memoryGraphInstance.isDisposed()) return;
                const data = res.data
                doMemoryGraph(memoryGraphInstance, data, height * .8, theme)
                if (virtualMemoryGraphInstance.isDisposed()) return;
                doVirtualMemoryGraph(virtualMemoryGraphInstance, data, height * .8, theme)
                setTimeout(loop, 1000);
            } catch (error) {
                console.error(error)
                window.messageApi.error("获取内存信息失败")
            }
        }

        loop().then()
        return () => {
            stopLoop = true
        }
    }, [theme, memoryGraphInstance]);

    return (
        <div className={styles.container}
             style={width < 600 ? {flexDirection: "column"} : {}}
        >
            <Card
                cover={
                    <EChartsFC
                        width={width < 1200 ? width / 2 : 600}
                        height={width < 1200 ? width / 2 : 600}
                        graphInit={(ins) => setMemoryGraphInstance(ins)}
                    />
                }
                className={"cardBody"}
            >
                {memoryInfo &&
                    <Collapse
                        ghost
                        items={memoryInfo.physicalMemory.map((item, index) => ({
                            key: index,
                            label: item.bankLabel,
                            classNames: {
                                body: "mCard"
                            },
                            styles: {
                                header: {fontSize: 17}
                            },
                            children: <>
                                <p>制造商<span>{item.manufacturer}</span></p>
                                <p>内存容量<span>{(item.capacity / 1024 / 1024 / 1024).toFixed(2)}GB</span></p>
                                <p>时钟评率<span>{item.clockSpeed / 1000 / 1000}Mhz</span></p>
                                <p>内存类型<span>{item.memoryType}</span></p>
                                <p>插槽标签<span>{item.bankLabel}</span></p>
                            </>,
                        }))}
                    />}
            </Card>
            <Card
                cover={
                    <EChartsFC
                        width={width < 1200 ? width / 2 : 600}
                        height={width < 1200 ? width / 2 : 600}
                        graphInit={(ins) => setVirtualMemoryGraphInstance(ins)}
                    />
                }
                className={"cardBody"}
            >
                <ul className="vmCard">
                    <li>总共可用的交换空间大小<span>{memoryInfo && memoryInfo.virtualMemory.swapTotal}</span></li>
                    <li>已使用的交换空间大小<span>{memoryInfo && memoryInfo.virtualMemory.swapUsed}</span></li>
                    <li>读取的分页文件<span>{memoryInfo && memoryInfo.virtualMemory.swapPagesIn}</span></li>
                    <li>存储的分页文件<span>{memoryInfo && memoryInfo.virtualMemory.swapPagesOut}</span></li>
                </ul>
            </Card>
        </div>
    )
}

export default MemoryCard
